
import './Scss.scss'
import { App, Tabs } from 'antd'
import { useMount } from 'ahooks'
import { CSS } from '@dnd-kit/utilities'
import { useState, cloneElement } from 'react'
import { DndContext, PointerSensor, useSensor } from '@dnd-kit/core'
import { arrayMove, horizontalListSortingStrategy, SortableContext, useSortable } from '@dnd-kit/sortable'

import Wijmo from '../../Router/Wijmo'
import Custom from '../../Router/Custom'
import ProTable from '../../Router/ProTable'
import { PutIndexedDB, GetIndexedDB } from '../../Utils/IndexedDB'
import { objectArrHas, objectArrValue } from '../../Utils/configFun'

const DraggableTabNode = ({ className, ...props }) => {
    const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props['data-node-key'] })
    const style = { ...props.style, transform: CSS.Translate.toString(transform), transition, cursor: 'move' }
    return cloneElement(props.children, { ref: setNodeRef, style, ...attributes, ...listeners })
}


const A01 = ({ PageEvent }) => {
    const TempMapping = (page) => ({
        Wijmo: <Wijmo page={page} />,
        Custom: <Custom page={page} PageEvent={PageEvent} />,
        ProTable: <ProTable page={page} />
    })

    const { modal } = App.useApp();
    const [items, setItems] = useState([])
    const [Active, setActive] = useState('11111111-1111-1111-1111-111111111111')

    const [BoxConfig, setBoxConfig] = useState()
    PageEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'openPage') getPage(data)
        if (type === 'updateBody') getInitTheme()
    })

    const getInitTheme = async () => {
        const config = await GetIndexedDB('theme')
        const { BoxConfig } = config.bodyConfig
        setBoxConfig(BoxConfig)
    }

    // 获取页面信息
    const getPage = async (data) => {
        const { type, page, key } = data
        if (!type || !page) modal.warning({ title: '当前菜单未配置!', content: `TYPE:${type} || PAGE:${page}` })
        else {
            if (!objectArrHas(items, key, 'key')) {
                console.info(`%c[${type}--${page}]`, 'color: #f759ab; font-size: 16px;')
                const list = [...items, { key, label: data.label, type, page, children: TempMapping(page)[type] }]
                PutIndexedDB('openPage', { list, active: key })
                setItems(list)
                setActive(key)
            } else {
                PutIndexedDB('openPage', { list: items, active: key })
                setActive(key)
            }
        }
    }
    const initPage = (data) => {
        const { list, active } = data
        const items = list.map(item => item = { ...item, children: TempMapping(item.page)[item.type] })
        setItems(items)
        setActive(active)
        setTimeout(() => PageEvent.emit({ type: 'openPage', data: objectArrValue(list, active, 'key') }), 0)
    }

    const sensor = useSensor(PointerSensor, { activationConstraint: { distance: 10 } })
    const onDragEnd = ({ active, over }) => {
        if (active.id !== over?.id) {
            setItems((prev) => {
                const activeIndex = prev.findIndex((i) => i.key === active.id)
                const overIndex = prev.findIndex((i) => i.key === over?.id)
                return arrayMove(prev, activeIndex, overIndex);
            })
        }
    }

    const onEdit = (targetKey, action) => {
        if (action === 'remove') {
            let active = Active
            const targetIndex = items.findIndex(v => v.key === targetKey)
            const list = items.filter(v => v.key !== targetKey)
            if (list.length && targetKey === Active) {
                const data = list[targetIndex === list.length ? targetIndex - 1 : targetIndex]
                PageEvent.emit({ type: 'openPage', data })
                active = data.key
                setActive(data.key)
            }
            PutIndexedDB('openPage', { list, active })
            setItems(list)
        }
    }

    const onChange = (e) => {
        PageEvent.emit({ type: 'openPage', data: objectArrValue(items, e, 'key') })
        setActive(e)
    }

    useMount(async () => {
        const data = await GetIndexedDB('openPage')
        if (data) initPage(data)
        else {
            const active = '11111111-1111-1111-1111-111111111111'
            const list = [{ key: active, label: '首页', type: 'Custom', page: 'Home', closable: false, children: <Custom page='Home' PageEvent={PageEvent} /> }]
            PutIndexedDB('openPage', { list, active })
            setItems(list)
            setActive(active)
        }
        getInitTheme()
    })

    if (BoxConfig) {
        return (
            <div className='BodyA01'>
                <div className='Body' style={{
                    '--background': BoxConfig.background,
                    '--backdropFilter': BoxConfig.backdropFilter,
                    '--padding': BoxConfig.padding,
                    '--borderRadius': BoxConfig.borderRadius
                }}>
                    <Tabs
                        hideAdd
                        items={items}
                        activeKey={Active}
                        type="editable-card"
                        onChange={onChange}
                        onEdit={onEdit}
                        renderTabBar={(tabBarProps, DefaultTabBar) => (
                            <DndContext sensors={[sensor]} onDragEnd={onDragEnd}>
                                <SortableContext items={items.map((i) => i.key)} strategy={horizontalListSortingStrategy}>
                                    <DefaultTabBar {...tabBarProps}>
                                        {(node) => <DraggableTabNode {...node.props} key={node.key}>{node}</DraggableTabNode>}
                                    </DefaultTabBar>
                                </SortableContext>
                            </DndContext>
                        )}
                    />
                </div>
            </div>
        )
    }
}

export default A01